package com.springvision.core.tcpclient;

import java.nio.charset.Charset;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;

import com.springvision.yuanfeng.core.tcp.YfCloudClientHandler;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

/**
 * netty客户端
 *
 * @author qwh
 */
@Configuration
public class NettyClientConfiguration {

	private Logger log = Logger.getLogger(this.getClass());

	// @Autowired
	// @Qualifier("tcpChannelOptions")
	// private Map<ChannelOption<?>, Object> tcpChannelOptions;

	// @Autowired
	// @Qualifier("clientChannelInitializer")
	// private ClientChannelInitializer clientChannelInitializer;

	@Autowired
	@Qualifier("clientChannelHandler")
	private YfCloudClientHandler yfCloudClientHandler;

	@Bean(name = "bootstrap")
	@Lazy(false)
	public Bootstrap bootstrap() throws Exception {
		Bootstrap b = new Bootstrap();
		b.group(clientGroup());
		b.channel(NioSocketChannel.class);
		// 保持长连接状态
		// b.option(ChannelOption.SO_KEEPALIVE, true);
		b.handler(new ChannelInitializer<Channel>() {

			@Override
			protected void initChannel(Channel ch) throws Exception {
				// TODO Auto-generated method stub
				ChannelPipeline pipeline = ch.pipeline();
				// ByteBuf delimiter = Unpooled.copiedBuffer("|".getBytes());
				// // 以("\n")为结尾分割的 解码器 Delimiters |
				// pipeline.addLast("framer", new
				// DelimiterBasedFrameDecoder(8192, delimiter));
				// 字符串解码 和 编码
				pipeline.addLast("decoder", new StringDecoder());
				pipeline.addLast("encoder", new StringDecoder(Charset.forName("GB2312")));
				pipeline.addLast("handler", yfCloudClientHandler);
			}
		});
		return b;
	}

	@Bean(name = "clientGroup", destroyMethod = "shutdownGracefully")
	public NioEventLoopGroup clientGroup() {
		return new NioEventLoopGroup(4);
	}

}
